package com.gitee.shigen.oss.cloud;

import com.gitee.shigen.common.exception.BaseException;
import com.gitee.shigen.oss.config.CloudStorageConfig;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.qiniu.util.IOUtils;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 腾讯云存储
 * <a href="https://cloud.tencent.com/document/product/436/10199">腾讯云COS Java sdk</a>
 *
 * @author shigenfu
 */
public class QcloudCloudStorageService extends CloudStorageService {

    private COSClient client;

    public QcloudCloudStorageService(CloudStorageConfig config) {
        this.config = config;

        //初始化
        init();
    }

    private void init() {
        // 不建议直接使用app-secret
        COSCredentials credentials = new BasicCOSCredentials(config.getQcloud().getSecretId(), config.getQcloud().getSecretKey());
        Region region = new Region(config.getQcloud().getRegion());

        ClientConfig clientConfig = new ClientConfig(region);
        clientConfig.setHttpProtocol(HttpProtocol.https);
        this.client = new COSClient(credentials, clientConfig);
    }

    @Override
    public String upload(byte[] data, String path) {
        //腾讯云必需要以"/"开头
        if (!path.startsWith("/")) {
            path = "/" + path;
        }

        //上传到腾讯云
        ObjectMetadata metaData = new ObjectMetadata();
        metaData.setContentLength(data.length);
        PutObjectRequest putObjectRequest = new PutObjectRequest(config.getQcloud().getBucketName(), path, new ByteArrayInputStream(data), metaData);
        PutObjectResult result = client.putObject(putObjectRequest);
        return config.getQcloud().getDomain() + path;
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        try {
            byte[] data = IOUtils.toByteArray(inputStream);
            return this.upload(data, path);
        } catch (IOException e) {
            throw new BaseException("上传文件失败");
        }
    }

    @Override
    public String uploadSuffix(byte[] data, String suffix) {
        return upload(data, getPath(config.getQcloud().getPrefix(), suffix));
    }

    @Override
    public String uploadSuffix(InputStream inputStream, String suffix) {
        return upload(inputStream, getPath(config.getQcloud().getPrefix(), suffix));
    }
}
